package com.ykq.sso.controller;

import com.alibaba.fastjson.JSON;
import com.ykq.pojo.dto.CommonResult;
import com.ykq.sso.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @program: education-parent
 * @description:
 * @author: 闫克起2
 * @create: 2022-08-03 10:44
 **/
@RestController
@RequestMapping("/sso")
@Slf4j
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/logout")
    public CommonResult logout(HttpServletRequest request){
        String token = request.getHeader("token");
        redisTemplate.delete(token);
        return new CommonResult(2000,"退出成功",null);
    }

    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginVO loginVO){
        Subject subject = SecurityUtils.getSubject();
        try{
            UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(loginVO.getUsername(),loginVO.getPassword());
            subject.login(usernamePasswordToken);

            Map<String,Object> map = (Map) subject.getPrincipals().getPrimaryPrincipal();

            //token的生成方式:UUID随机生成  （2）jwt来生成token【把一些写入放入到token】
            String token = UUID.randomUUID().toString();
            //把token作为key，把用户信息和权限作为value存入redis.
            redisTemplate.opsForValue().set(token, JSON.toJSONString(map),24, TimeUnit.HOURS);
            return new CommonResult(2000,"登录成功",token);
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult(5000,"登录失败",null);
        }
    }
}
